package com.abyss.batch;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.MapOperator;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

import java.util.Arrays;

/**
 * @author Abyss
 * @date 2020/10/4
 * @description
 */
public class BatchWordCountLambdaDemo {
    public static void main(String[] args) throws Exception {
        // 1. get env
        // 当前是批处理，使用批处理的env对象,ExecutionEnvironment
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        // 2. 获取数据（数据输入)
        DataSource<String> source = env.fromElements(
                "hadoop spark hadoop",
                "spark hadoop spark",
                "hadoop flink spark"
        );

        // 3. 处理
        FlatMapOperator<String, String> wordsDataset = source.flatMap(
                (String value, Collector<String> out) -> {
                    String[] words = value.split(" ");
//                    for (String word: words) {
//                        out.collect(word);
//                    }
                    Arrays.stream(words).forEach(out::collect);
                }
        ).returns(Types.STRING);

        MapOperator<String, Tuple2<String, Integer>> wordWithOne = wordsDataset.map((String value) -> {
            return Tuple2.of(value, 1);
        }).returns(Types.TUPLE(Types.STRING, Types.INT));

        AggregateOperator<Tuple2<String, Integer>> result = wordWithOne.groupBy(0).sum(1);

        result.print();
    }
}
